package com.crane.framework.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.crane.framework.dto.common.TreeNodeDTO;
import com.crane.framework.entity.Menu;
import com.crane.framework.entity.Role;
import com.crane.framework.entity.RoleMenu;
import com.crane.framework.entity.User;
import com.crane.framework.service.*;
import com.crane.framework.utils.CommonUtil;
import com.crane.framework.utils.SystemUtil;
import com.crane.framework.vo.MenuVO;
import com.crane.framework.vo.SelfInfoDTO;
import com.crane.framework.vo.TotalBaseInfoVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Tag(name = "公共接口 API")
@RestController
@RequestMapping("/api/v1.0/public")
public class PublicController {
  @Resource private IMenuService menuService;
  @Resource private IUserService userService;
  @Resource private IRoleMenuService roleMenuService;
  @Resource private IFileService fileService;
  @Resource private IUserRoleService userRoleService;

  @Operation(summary = "基础信息")
  @GetMapping("/totalBaseInfo")
  public TotalBaseInfoVO totalBaseInfo() {
    Object loginId = StpUtil.getLoginId();

    // 获取用户信息
    User user = userService.getById(loginId.toString());
    user.setPassword(null);
    List<Role> roleList = userRoleService.getRoleListByUserId(user.getId());

    if (CommonUtil.isNullOrEmpty(roleList)) {
      return null;
    }

    List<String> roleIdList = roleList.stream().map(Role::getId).toList();

    TotalBaseInfoVO totalBaseInfoVO = new TotalBaseInfoVO();

    SelfInfoDTO selfInfoDTO = SystemUtil.buildResource(user, SelfInfoDTO.class);
    fileService.transfer(selfInfoDTO);

    totalBaseInfoVO.setSelfInfoDTO(selfInfoDTO);

    // 获取角色菜单关联表信息
    List<RoleMenu> roleMenuList =
        roleMenuService.lambdaQuery().in(RoleMenu::getRoleId, roleIdList).list();
    if (CommonUtil.isNullOrEmpty(roleMenuList)) {
      return totalBaseInfoVO;
    }

    // 获取菜单id集合
    List<String> menuId = roleMenuList.stream().map(RoleMenu::getMenuId).toList();

    List<MenuVO> menuTree = menuService.getMenuList(menuId, null);

    totalBaseInfoVO.setMenuTree(menuTree);

    return totalBaseInfoVO;
  }
}
